const express = require('express');
const cookieParser = require('cookie-parser'); //cookie
const logger = require('morgan'); // 日志
const compression = require('compression'); // gzip压缩
const cors = require('cors'); // 解决跨域问题
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const redis = require('redis');
const path = require('path');
const conf = require(path.join(__dirname,'/src/conf'))
const indexRouter = require(path.join(__dirname,'src/routes/index'));
const loginRouter = require(path.join(__dirname,'src/routes/login'));
const app = express();

app.set('trust proxy', 1);
app.use(compression());
app.use(cors(conf.cors)); // 不加上这句代码跨域访问时会出现错误，加上就不会出现跨域错误情况
app.use(logger(conf.logLevel));
app.use(express.json()); // 解析json编码数据
app.use(express.urlencoded({ extended: false })); // 解析url编码的数据
app.use(session({
  name: conf.session.name, // 保存在本地cookie的一个名字 默认connect.sid  可以不设置
  secret: conf.session.secret, // 可以随便写。 一个 String 类型的字符串，作为服务器端生成 session 的签名
  resave: conf.session.resave, // 强制保存session,即使它没有变化,默认false
  saveUninitialized: conf.session.saveUninitialized, // 强制将未初始化的 session 存储。  默认值是true  建议设置成true
  rolling: conf.session.rolling, //在每次请求时强行设置 cookie，这将重置 cookie 过期时间（默认：false） 
  cookie: conf.cookie,
  store: new RedisStore({client: redis.createClient(conf.redis)})
}));
app.use(cookieParser('cpsxs01',conf.cookie));

app.use('/', indexRouter);
app.use('/login', loginRouter);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  res.status(404);
  res.jsonp({
    code: 404,
    data: "The path is lost in the wind."
  });
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);
  res.jsonp({
    code: 500,
    data: "There is something wrong with the server,You can contact the admin to solve it."
  });
});

module.exports = app;